package com.whg.demo.controller;


import com.whg.demo.model.Article;
import com.whg.demo.model.JsonData;
import com.whg.demo.repository.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author whg
 * @create 2022/12/13 14:54
 * @description：
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @PostMapping("/save")
    public JsonData save(@RequestBody Article article){
        articleRepository.save(article);
        return JsonData.buildSuccess();
    }

    @PostMapping("/query")
    public JsonData query(@RequestBody Article article){
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title",article.getTitle());
        Iterable<Article> iterable = articleRepository.search(queryBuilder);
        Iterator<Article> iterator = iterable.iterator();
        List<Article> list = new ArrayList<>();
        while (iterator.hasNext()){
            list.add(iterator.next());
        }
        return JsonData.buildSuccess(iterable);
    }
}
